#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <string>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cerrno>

void Usage()
{
    std::cout << "you can use " << "IP and " << "Port" << std::endl; 
}
int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage();
        return 1;
    }
    //1.创建套接字
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if(sock < 0)
    {
        std::cerr << "sock error " << std::endl;
        return 2;
    }
    //2.你要给谁发
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(atoi(argv[2]));
    server.sin_addr.s_addr = inet_addr(argv[1]);
    //3.使用服务
#define NUM 1024
    while(true)
    {
        char buffer[NUM] = {0};
        std::cout << "请输入# ";
        fgets(buffer, sizeof(buffer), stdin);
        sendto(sock, buffer, sizeof(buffer), 0, (struct sockaddr*)&server, sizeof(server));

        struct sockaddr_in tmp;
        socklen_t len = sizeof(tmp);
        char ret[2*NUM] = {0};
        ssize_t result = recvfrom(sock, ret, sizeof(ret), 0, (struct sockaddr*)&tmp, &len);
        if(result > 0)
            std::cout << ret << std::endl;
    }

    return 0;
}